package com.codeoss.framework.db.service.impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;

import org.springframework.beans.factory.annotation.Autowired;

import com.codeoss.framework.data.metadata.Column;
import com.codeoss.framework.data.metadata.Table;
import com.codeoss.framework.db.service.IDDLService;
import com.codeoss.framework.util.DBUtil;


public abstract class AbstractDDLService implements IDDLService {
	@Autowired
	private DBUtil dbUtil;
    public void createTable(Connection connection,Table table) {
		Statement stmt=null;
		String sql=null;
		try {
			stmt=connection.createStatement();
			sql=getCreateTableSql(table);
			stmt.execute(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(sql,e);
		}finally {
			dbUtil.closeStatement(stmt);
		}
    }
	
	public void createColumn(Connection connection,Table table,Column column) {
		Statement stmt=null;
		String sql=null;
		try {
			stmt=connection.createStatement();
			sql=getCreateColumnSql(table,column);
			stmt.execute(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(sql,e);
		}finally {
			dbUtil.closeStatement(stmt);
		}
	}
	
	public void createUniqueIndex(Connection connection,Table table,Column column) {
		Statement stmt=null;
		String sql=null;
		try {
			stmt=connection.createStatement();
			sql=getCreateUniqueIndexSql(table,column);
			stmt.execute(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(sql,e);
		}finally {
			dbUtil.closeStatement(stmt);
		}
	}
	
	public void createForeignKey(Connection connection,Table table,Column column) {
		Statement stmt=null;
		String sql=null;
		try {
			stmt=connection.createStatement();
			sql=getCreateForeignKeySql(table,column);
			stmt.execute(sql);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(sql,e);
		}finally {
			dbUtil.closeStatement(stmt);
		}
	}
	
	public void createView(Connection connection,Table table) {
		Statement stmt=null;
		String sql=null;
		try {
			stmt=connection.createStatement();
			StringBuilder sqlBuilder=new StringBuilder();
			sqlBuilder.append("CREATE OR REPLACE VIEW ").append(table.getTableName());
			sqlBuilder.append(" AS ").append(table.getSql());
			stmt.execute(sqlBuilder.toString());
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(sql,e);
		}finally {
			dbUtil.closeStatement(stmt);
		}
	}
	
	public abstract String getCreateTableSql(Table table);
	
	public abstract String getCreateColumnSql(Table table,Column column);
	
	public abstract String getCreateUniqueIndexSql(Table table,Column column);
	
	public abstract String getCreateForeignKeySql(Table table,Column column);
}
